/*
 * @Author: 熊志伟 xiongzhiwei
 * @Date: 2024-11-08 13:34:26
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-06 14:27:43
 * @FilePath: \sr_system_manager_ui\src\store\modules\user.ts
 * @Description: user store
 */
import { getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import { ResourceDetailVO } from '@/api/system/user/type'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      phone: '',
      permissions: [],
      menuList: [],
      identityCode: [],
      email: '',
      currentIdentityCode: '',
      departmentId: '', // 学院（部）id
      departmentName: '', // 学院（部）名称
      code: '', // 工号
    }),
    actions: {
      // 登录
      login(token) {
        setToken(token)
        this.token = token
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then((res:ResourceDetailVO) => {
            
            const user = res
            const avatar = user.avatar ? import.meta.env.VITE_APP_BASE_API + user.avatar : defAva;

            if (res.roleList && res.roleList.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roleList
              this.permissions = res.perms
            } else {
              this.roles = ["ROLE_DEFAULT"];
            }
            this.id = user.accountId
            this.name = user.accountName
            this.email = user.email
            this.avatar = avatar
            this.phone = user.phone
            this.menuList = user.menuList
            this.identityCode = user.identityCode
            this.currentIdentityCode = user.currentIdentityCode
            this.departmentId = user.departmentId
            this.departmentName = user.departmentName
            this.code = user.code
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve) => {
          // logout(this.token).then(() => {
          //   this.token = ''
          //   this.roles = []
          //   this.permissions = []
          //   removeToken()
          //   resolve()
          // }).catch(error => {
          //   reject(error)
          // })
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
        })
      }
    }
  })

export default useUserStore;
